import React, {Component, PropTypes} from 'react';
import {StyleSheet, View, ListView, Text, Image, TouchableOpacity, TouchableHighlight} from 'react-native';

import {screenWidth, screenHeight} from '../communals/MyExports.js';

/**
 * 筛选菜单组件
 * Created by 10691 on 17/5/19.
 */
export default class FilterMenu extends Component {

    static propTypes = {
        // 菜单里的数据
        data: PropTypes.array.isRequired,
        myStyle: Text.propTypes.style,
        loadFilteredData: PropTypes.func,     // 点击菜单项回调
        removeModal: PropTypes.func,     // 销毁模态modal回调
    };

    constructor() {
        super();
        this.state = {
            dataSource: new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}),
        };
        this.renderRow = this.renderRow.bind(this);
    }

    componentDidMount() {
        this.loadData();
    }

    /**
     * 加载数据
     */
    loadData() {
        this.setState({dataSource: this.state.dataSource.cloneWithRows(this.props.data)});
    }

    render() {
        return (
            <TouchableOpacity
                onPress={() => this.props.removeModal()}
                activeOpacity={1}>
                <View style={[this.props.myStyle, {width: screenWidth, height: screenHeight}]}>
                    <ListView dataSource={this.state.dataSource}
                              renderRow={this.renderRow}
                              initialListSize={16}
                              contentContainerStyle={FilterMenuStyles.contentViewStyle}/>
                </View>
            </TouchableOpacity>
        );
    }

    /**
     * 渲染Item
     */
    renderRow(rowData) {
        return (
            <View>
                <TouchableHighlight
                    onPress={() => this.clickItem(rowData.mall, rowData.cate)}>
                    <View style={FilterMenuStyles.itemViewStyle}>
                        <Image source={{uri: rowData.image}} style={FilterMenuStyles.itemImageStyle}/>
                        <Text>{rowData.title}</Text>
                    </View>
                </TouchableHighlight>
            </View>
        );
    }

    /**
     * 点击Item项
     */
    clickItem(mall, cate) {
        this.props.loadFilteredData(mall, cate);
        this.props.removeModal();
    }
}

const FilterMenuStyles = StyleSheet.create({
    contentViewStyle: {
        flexDirection: 'row',
        flexWrap: 'wrap',
    },

    itemViewStyle: {
        width: screenWidth * 0.25,
        height: 70,
        backgroundColor: '#f4f4f4',
        justifyContent: 'center',
        alignItems: 'center'
    },

    itemImageStyle: {
        width: 40,
        height: 40
    }

});